package cn.picclife.mwx.manager.sys.controller;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.picclife.mwx.app.util.AmazonS3Utils;
import cn.picclife.mwx.app.util.PropertiesUtil;
//import cn.picclife.mwx.common.web.controller.ApiBaseController;
import cn.picclife.mwx.manager.base.BaseResult1;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.UserSessionBo;
import cn.picclife.mwx.manager.sys.model.po.TTask;
import cn.picclife.mwx.manager.sys.model.po.TTaskNode;
import cn.picclife.mwx.manager.sys.service.TaskMgMtService;
import cn.picclife.mwx.manager.util.Constant;
import cn.picclife.mwx.manager.util.RestUtils;


/**
 * 双录任务控制器
 */
@Controller
@RequestMapping("/api")
public class TaskMgMtApiController /*extends ApiBaseController*/{
	
	@Autowired
	private TaskMgMtService taskMgMtService;
	
	/**
	 * @Title: queryTask
	 * @Description: 查询双录任务列表
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping("/task/query_task")
	@ResponseBody
	public PageCount queryTask(HttpServletRequest req, HttpServletResponse res, PageCount pageCount) {
		PageCount pageQuery = taskMgMtService.queryTask(pageCount);
		return pageQuery;
	}

	/***
	 * 查询双录节点审核详情
	 * @param request
	 * @param taskId
	 * @return
	 */
	@RequestMapping(value = "/task/query_task_node_approve")
	@ResponseBody
	public Map<String, Object> queryTaskNodeApprove(HttpServletRequest request, @RequestParam("taskId")int taskId) {
		Map<String,Object> result = new HashMap<String,Object>();
		//查询双录任务
		TTask task = taskMgMtService.queryByTaskId(taskId);
		result.put("task", task);
		//查询双录节点审核信息
		List<Map<String,String>> taskNodeApprove = taskMgMtService.getTaskNodeApprove(taskId);
		result.put("taskNodeApprove", taskNodeApprove);
		return result;
	}
	
	
	/***
	 * 保存节点审核
	 * @param request
	 * @param response
	 * @param taskId
	 * @param nodeId
	 * @param approveMemo
	 * @param approveState
	 * @return
	 */
	@RequestMapping(value="/task/update_node_approve")
	@ResponseBody
	public BaseResult1 addRoles(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("taskId") int taskId,@RequestParam("nodeId") int nodeId,@RequestParam("approveMemo") String 
			approveMemo,@RequestParam("approveState") int approveState,@RequestParam("approveId") int approveId) {
		if(approveMemo.equals("null")){
			approveMemo="";
		}
		BaseResult1 result = new BaseResult1();
		UserSessionBo userSessionBo = (UserSessionBo)request.getSession().getAttribute("user");
		String optNo = userSessionBo.getOptNo();
		//修改审核之前 也需要判断 次节点的上传和录制状态 都为2的话 才可以审核
		TTaskNode tasknode = taskMgMtService.queryByNodeId(taskId,nodeId);
		if(!tasknode.getRecordState().equals("2")&&tasknode.getUploadState().equals("2")){
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("节点未录制或者上传，无法进行审核操作");
			RestUtils.error(response, result);
			return result;
		}
		if(tasknode.getApproveState().equals(2)){
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("已经通过的节点无法再审核");
			RestUtils.error(response, result);
			return result;
		}
		//如果节点状态已经是通过了，否则不能再改为不通过
		boolean returnValue = false;
		//修改审核
		if(approveId > 0) {
				returnValue = taskMgMtService.updateTaskNodeApprove(taskId,nodeId,approveMemo,optNo,approveState);
		}else {//新增审核
			returnValue = taskMgMtService.saveTaskNodeApprove(taskId,nodeId,approveMemo,optNo,approveState);
		}
		//更新成功后，需要更新Task上的双录任务状态
		if(returnValue) {
			//查询所有结点属否都审核了，如果没审核那样就不修改task状态
			int nodeApproveCount = taskMgMtService.queryNodeApproveCounts(taskId);
			if(nodeApproveCount==12){
				// 查询节点通过数量
				int nodePassCount = taskMgMtService.queryTaskNodePassCount(taskId);
				if(nodePassCount == Constant.TASK_NODE_COUNT) {
					//12个通过
					taskMgMtService.updateTask(taskId,Constant.TASK_STATE_PASS,new Date());
				}else{
				//更新t_task 变成审核未通过	 task_state=4 
					taskMgMtService.updateTaskNoPass(taskId,Constant.TASK_STATE_NO_PASS,new Date());
				}
				/*int nodeApproveCount = taskMgMtService.queryTaskNodeApproveCount(taskId);
				if(nodeApproveCount == Constant.TASK_NODE_COUNT) {
					int nodeNoPassCount = taskMgMtService.queryTaskNodeNoPassCount(taskId);
					if(nodeNoPassCount > 0) {
						taskMgMtService.updateTask(taskId,Constant.TASK_STATE_NO_PASS,new Date());
					}
				}*/
			}
		}
		
		if (returnValue) {
			result.setRet(BaseResult1.SUCCESS);
			result.setMsg("操作成功");
			return result;
		} else {
			result.setRet(BaseResult1.BIZ_ERROR);
			result.setMsg("操作失败");
			RestUtils.error(response, result);
			return result;
		}
	}
	
	
	/***
	 * 下载文件
	 * @param fileId 文件Id
	 * @return 云服务器
	 * @throws IOException 
	 */
	@RequestMapping(value="/task/file/download",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,String> downloadFile(HttpServletRequest req, HttpServletResponse response, @RequestParam("fileId") String fileId) throws IOException {
		//BaseResult result = new BaseResult();
		Map<String,String> map = new HashMap<String,String>();
		String file_name=taskMgMtService.QueryFileUrl(fileId);
		String server_url=PropertiesUtil.getOSPropBySrc("upload", "server_url");
		//根据file id 查询 taskId和nodeoid
		//TTask task = taskMgMtService.queryNodeByfileid(fileId);
		map.put("download_url", server_url+file_name);
		//获取webapps的路径
//		String path=System.getProperty("user.dir").replace("bin", "webapps");
//		String file_path="D:\\EclipseForJavaEE\\apache-tomcat-8.0.39\\webapps\\image\\1.mp4";
//		File file = new File(file_path);
//		if(file==null){
//			result.setRet(BaseResult.BIZ_ERROR);
//			result.setMsg("操作失败");
//			RestUtils.error(response, result); 
//			return result;
//		}
//		String filename = file.getName();
//		InputStream fis = new BufferedInputStream(new FileInputStream(file_path));
//		byte[] buffer = new byte[fis.available()];
//	      fis.read(buffer);
//	      fis.close();
//	   // 清空response
//	      response.reset();
//	      // 设置response的Header
//	      response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
//	      response.addHeader("Content-Length", "" + file.length());
//	      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//	      response.setContentType("application/octet-stream");
//	      toClient.write(buffer);
//	      toClient.flush();
//	      toClient.close();
		return map;
	}
	
}
